﻿using ERPWinFormWork.Material.Material.Dtos;
using ERPWinFormWork.Material.MaterialCode;
using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace ERPWinFormWork.Material
{
    public partial class GetMaterial : Form
    {
        public GetMaterial()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);

            // 设置占位提示为水印，不作为实际输入内容
            stbName.Text = string.Empty;
            stbName.WaterText = "请输入物料名称";
            stbName.SkinTxt.Text = string.Empty;
            stbName.SkinTxt.WaterText = "请输入物料名称";

            scboType_Id.SelectedIndex = -1;
            scboType_Id.Text = string.Empty;
            scboType_Id.WaterText = "请选择物料类型";

            scboProperties_Id.SelectedIndex = -1;
            scboProperties_Id.Text = string.Empty;
            scboProperties_Id.WaterText = "请选择物料属性";

            scbClassification_Id.SelectedIndex = -1;
            scbClassification_Id.Text = string.Empty;
            scbClassification_Id.WaterText = "请选择物料分类";

            stblimit.Text = string.Empty;
            stblimit.WaterText = "请输入库存上限";
            stblimit.SkinTxt.Text = string.Empty;
            stblimit.SkinTxt.WaterText = "请输入库存上限";

            stblower.Text = string.Empty;
            stblower.WaterText = "请输入库存下限";
            stblower.SkinTxt.Text = string.Empty;
            stblower.SkinTxt.WaterText = "请输入库存下限";


            tbxInputName.Text = string.Empty;
            tbxInputName.WaterText = "请输入入库单名称";
            tbxInputName.SkinTxt.Text = string.Empty;
            tbxInputName.SkinTxt.WaterText = "请输入入库单名称";


            tbxordernumber.Text = string.Empty;
            tbxordernumber.WaterText = "请输入来料检验编号";
            tbxordernumber.SkinTxt.Text = string.Empty;
            tbxordernumber.SkinTxt.WaterText = "请输入来料检验编号";



            tbxlingliao.Text = string.Empty;
            tbxlingliao.WaterText = "请输入领料编号";
            tbxlingliao.SkinTxt.Text = string.Empty;
            tbxlingliao.SkinTxt.WaterText = "请输入领料编号";



            tbxrenwu.Text = string.Empty;
            tbxrenwu.WaterText = "请输任务编号";
            tbxrenwu.SkinTxt.Text = string.Empty;
            tbxrenwu.SkinTxt.WaterText = "请输入任务编号";

            tbxgongxu.Text = string.Empty;
            tbxgongxu.WaterText = "请输入工序名称";
            tbxgongxu.SkinTxt.Text = string.Empty;
            tbxgongxu.SkinTxt.WaterText = "请输入工序名称";

   



            // 初始化时间控件
            dtplingliaodate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            dtplingliaodate.text = "请选择领料日期";
           

            GetData();
            LoadTypeData();
            LoadPropertiesData();
            LoadClassificationData();
            
   
            GetMaterialInputData();

            GetMaterialOutData();
            GetContractData();
            LoadSupplierData();

        }

        private ApiClient _apiClient;
        //物料库存的分页
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;


        //生产领料的分页
        private int PageIndexIn { get; set; } = 1;
        private int PageSizeIn { get; set; } = 15;
        private int TotalCountIn { get; set; } = 0;
        private int TotalPagesIn { get; set; } = 0;

        //采购入库的分页
        private int PageIndexOut { get; set; } = 1;
        private int PageSizeOut { get; set; } = 15;
        private int TotalCountOut { get; set; } = 0;
        private int TotalPagesOut { get; set; } = 0;



        //采购合同的分页
        private int PageIndexContract { get; set; } = 1;
        private int PageSizeContract { get; set; } = 15;
        private int TotalCountContract { get; set; } = 0;
        private int TotalPagesContract { get; set; } = 0;

        private void btnAdd_Click(object sender, EventArgs e)
        {
           
        }


        // 定义用于解析登录响应的模型类
        public class ApiResponse<T>
        {
           public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data {  get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }
        /// <summary>
        /// 物料库存显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<MaterialDtos>>>(
                    endpoint: "Material/GetMaterialShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 更新分页信息
                TotalCount = response.totalCount;
                TotalPages = (response.totalCount + PageSize - 1) / PageSize;
                
                // 将数据绑定到 DataGridView
                dgvGetMaterial.DataSource = response.pageData;
                UpdatePage();


            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtncheck_Click(object sender, EventArgs e)
        {
            
            
            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(stbName.Text))
            {
                queryParams["materialName"] = stbName.Text;
            }
         
            // 类型ID（从下拉框选的值）
            if (scboType_Id.SelectedValue != null)
            {
                queryParams["type_Id"] = ((int)scboType_Id.SelectedValue).ToString();
            }
           
           
            // 属性ID（从下拉框选的值）
            if (scboProperties_Id.SelectedValue != null)
            {
                queryParams["properties_Id"] = ((int)scboProperties_Id.SelectedValue).ToString();
            }

            // 分类ID（从下拉框选的值）
            if (scbClassification_Id.SelectedValue != null)
            {
                queryParams["classification_Id"] = ((int)scbClassification_Id.SelectedValue).ToString();
            }
            //库存上限
            if (!string.IsNullOrEmpty(stblimit.Text))
            {
                if (int.TryParse(stblimit.Text, out int limit))
                {
                    queryParams["inventory_Iimit"] = limit.ToString();
                }
                else
                {
                    MessageBox.Show("库存上限必须是整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return; // 终止查询
                }
            }
            //库存下限
            if (!string.IsNullOrEmpty(stblower.Text))
            {
                if (int.TryParse(stblower.Text, out int lower))
                {
                    queryParams["lower_limit"] = lower.ToString();
                }
                else
                {
                    MessageBox.Show("库存下限必须是整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            // 重置页码到第一页
            PageIndex = 1;
            
            // 调用改造后的 GetData，传入查询条件
            GetData(queryParams);
        }
        /// <summary>
        /// 物料类型下拉框
        /// </summary>
        /// <returns></returns>
        private async void LoadTypeData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<Material_TypeDtos>>>(
                    endpoint: "Material/GetMaterialTypeShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    scboType_Id.Items.Clear();
                    scboType_Id.DisplayMember = "typeName"; 
                    scboType_Id.ValueMember = "id";
                    scboType_Id.DataSource=deptResponse.data;
                    scboType_Id.SelectedIndex = -1;
                   

                }

               
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 物料属性下拉框
        /// </summary>
        /// <returns></returns>
        private async void LoadPropertiesData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<Material_PropertiesDtos>>>(
                    endpoint: "Material/GetMaterialPropertiesShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    scboProperties_Id.Items.Clear();
                    scboProperties_Id.DisplayMember = "propertiesName";
                    scboProperties_Id.ValueMember = "id";
                    scboProperties_Id.DataSource = deptResponse.data;
                    scboProperties_Id.SelectedIndex = -1;

                 

                }


            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 物料分类下拉框
        /// </summary>
        /// <returns></returns>
        private async void LoadClassificationData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<Material_ClassificationDtos>>>(
                    endpoint: "Material/GetMaterialClassificationShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    scbClassification_Id.Items.Clear();
                    scbClassification_Id.DisplayMember = "classificationName";
                    scbClassification_Id.ValueMember = "id";
                    scbClassification_Id.DataSource = deptResponse.data;
                    scbClassification_Id.SelectedIndex = -1;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 采购入库添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddMaterialInput_Click(object sender, EventArgs e)
        {
            MaterialInput input=new MaterialInput();
            input.Show();
        }
        /// <summary>
        /// 采购入库显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetMaterialInputData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndexOut.ToString() },
                    { "PageSize", PageSizeOut.ToString() },
                    { "Material_InOutType", "2" } // 只显示入库数据（采购入库）
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                    // 调试输出：显示所有查询参数
                    Console.WriteLine($"入库查询参数: {kv.Key} = {kv.Value}");
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<MaterialInputDtos>>>(
                    endpoint: "Material/GetMaterial_InOutboundShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {


                // 更新分页信息
                TotalCountOut = response.totalCount;
                TotalPagesOut = (response.totalCount + PageSizeOut - 1) / PageSizeOut;
                UpdatePageOut();
                // 将数据绑定到 DataGridView
                dgvMaterialInput.DataSource = response.pageData;
                
                // 添加操作列
                AddMaterialInputOperationColumns();
                
                // 先解绑之前的事件，避免重复绑定
                dgvMaterialInput.CellClick -= DgvMaterialInput_CellClick;
                dgvMaterialInput.CellFormatting -= DgvMaterialInput_CellFormatting;
                
                // 重新绑定单元格点击事件和格式化事件
                dgvMaterialInput.CellClick += DgvMaterialInput_CellClick;
                dgvMaterialInput.CellFormatting += DgvMaterialInput_CellFormatting;
              
            }
            else
            {
                // 调试输出：显示API响应错误信息
                Console.WriteLine($"入库API响应失败: code={response?.code}, message={response?.message}");
                if (response?.pageData != null)
                {
                    Console.WriteLine($"入库数据条数: {response.pageData.Count}");
                }
            }
        }

        /// <summary>
        /// 为采购入库表格添加操作列
        /// </summary>
        private void AddMaterialInputOperationColumns()
        {
            // 清除现有的操作列（如果存在）
            if (dgvMaterialInput.Columns.Contains("CheckBox"))
            {
                dgvMaterialInput.Columns.Remove("CheckBox");
            }
            if (dgvMaterialInput.Columns.Contains("Input"))
            {
                dgvMaterialInput.Columns.Remove("Input");
            }
            if (dgvMaterialInput.Columns.Contains("Edit"))
            {
                dgvMaterialInput.Columns.Remove("Edit");
            }
            if (dgvMaterialInput.Columns.Contains("Delete"))
            {
                dgvMaterialInput.Columns.Remove("Delete");
            }

            // 检查数据源中是否有数据
            if (dgvMaterialInput.DataSource == null || dgvMaterialInput.Rows.Count == 0)
            {
                return;
            }

            // 添加复选框列（放在最前面）
            var checkBoxCol = new DataGridViewCheckBoxColumn
            {
                Name = "CheckBox",
                HeaderText = "选择",
                Width = 50,
                TrueValue = true,
                FalseValue = false
            };
            dgvMaterialInput.Columns.Insert(0, checkBoxCol);

            // 添加入库按钮列（始终添加，但通过CellFormatting事件控制显示）
            var inputCol = new DataGridViewButtonColumn
            {
                Name = "Input",
                HeaderText = "入库",
                Text = "入库",
                UseColumnTextForButtonValue = true,
                Width = 60
            };
            dgvMaterialInput.Columns.Add(inputCol);

            // 添加编辑按钮列
            var editCol = new DataGridViewButtonColumn
            {
                Name = "Edit",
                HeaderText = "编辑",
                Text = "编辑",
                UseColumnTextForButtonValue = true,
                Width = 60
            };

            // 添加删除按钮列
            var deleteCol = new DataGridViewButtonColumn
            {
                Name = "Delete",
                HeaderText = "删除",
                Text = "删除",
                UseColumnTextForButtonValue = true,
                Width = 60
            };

            // 添加编辑和删除列到表格
            dgvMaterialInput.Columns.Add(editCol);
            dgvMaterialInput.Columns.Add(deleteCol);
        }

        /// <summary>
        /// 采购入库表格单元格格式化事件
        /// 用于控制入库按钮的显示/隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvMaterialInput_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;

            // 只处理入库按钮列
            if (columnName == "Input")
            {
                // 获取当前行的数据
                if (grid.Rows[e.RowIndex].DataBoundItem is MaterialInputDtos materialInput)
                {
                    // 如果状态为true（已勾选），则隐藏入库按钮
                    if (materialInput.Status)
                    {
                        // 将按钮文本设为空，实现隐藏效果
                        e.Value = "";
                        e.FormattingApplied = true;
                    }
                    else
                    {
                        // 如果状态为false（未勾选），则显示入库按钮
                        e.Value = "入库";
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        /// <summary>
        /// 采购入库表格单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvMaterialInput_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;

            // 获取当前行的数据
            if (grid.Rows[e.RowIndex].DataBoundItem is MaterialInputDtos materialInput)
            {
                switch (columnName)
                {
                    case "Input":
                        // 检查状态，如果已勾选则不执行入库操作
                        if (materialInput.Status)
                        {
                            MessageBox.Show("该记录状态已勾选，无法执行入库操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        
                        // 调用后端接口修改状态为已勾选
                        UpdateMaterialInputStatus(materialInput.Id, true);
                        break;

                    case "Edit":
                        // 编辑操作
                        MessageBox.Show($"编辑入库记录", "编辑", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 编辑完成后刷新数据
                        GetMaterialInputData();
                        break;

                    case "Delete":
                        // 删除操作
                        var result = MessageBox.Show($"确定要删除这条入库记录吗？", "确认删除", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        
                        if (result == DialogResult.Yes)
                        {
                            // 调用后端删除接口
                            DeleteMaterialInputRecord(materialInput.Id);
                        }
                        break;
                }
            }
        }

        /// <summary>
        /// 删除入库记录
        /// </summary>
        /// <param name="id">入库记录ID</param>
        private async void DeleteMaterialInputRecord(int id)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的入库记录ID，无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除操作
                var result = MessageBox.Show($"确定要删除ID为 {id} 的入库记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 构建删除API端点
                string endpoint = $"Material/DeleteMaterialInOut?id={id}";
                Console.WriteLine($"删除请求URL：{endpoint}");

                // 调用删除API
                var response = await _apiClient.DeleteAsync<ApiResponse<string>>(
                    endpoint: endpoint,
                    parameters: null
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show($"成功删除入库记录", "删除成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 刷新数据
                    GetMaterialInputData();
                }
                else
                {
                    MessageBox.Show($"删除失败：{response?.message ?? "未知错误"}", "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除过程中出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"删除异常详情：{ex.StackTrace}");
            }
        }


        /// 更新入库记录状态
        /// </summary>
        /// <param name="id">入库记录ID</param>
        /// <param name="status">新状态</param>
        private async void UpdateMaterialInputStatus(int id, bool status)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的入库记录ID，无法更新状态", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 创建状态更新对象
                var statusUpdateData = new MaterialOutputStatusUpdateDto
                {
                    Id = id,
                    Status = status
                };

                // 构建查询参数
                var queryParams = new Dictionary<string, string>
                {
                    { "id", id.ToString() },
                    { "status", status.ToString().ToLower() }
                };

                // 构建带查询参数的endpoint
                var endpointWithParams = "Material/UpdateStatus?" + string.Join("&",
                    queryParams.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));

                var response = await _apiClient.PutAsync<object, ApiResponse<string>>(
                      endpoint: endpointWithParams,
                      data: null
                  );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("入库记录状态更新成功！", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新入库数据
                    GetMaterialInputData();

                    // 勾选对应的复选框（根据id找到对应的行并勾选）
                    CheckCorrespondingInputCheckbox(id, status);
                }
                else
                {
                    // 业务报错（如"未找到记录"），回滚复选框状态
                    MessageBox.Show($"状态更新失败：{response?.message ?? "未知错误"}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新入库记录状态时发生错误：{ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);


            }
        }

        /// <summary>
        /// 重置物料库存页面的所有输入控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtndelete_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置物料名称输入框
                stbName.Text = string.Empty;
                stbName.WaterText = "请输入物料名称";
                stbName.SkinTxt.Text = string.Empty;
                stbName.SkinTxt.WaterText = "请输入物料名称";

                // 重置物料类型下拉框
                scboType_Id.SelectedIndex = -1;
                scboType_Id.Text = string.Empty;
                scboType_Id.WaterText = "请选择物料类型";

                // 重置物料属性下拉框
                scboProperties_Id.SelectedIndex = -1;
                scboProperties_Id.Text = string.Empty;
                scboProperties_Id.WaterText = "请选择物料属性";

                // 重置物料分类下拉框
                scbClassification_Id.SelectedIndex = -1;
                scbClassification_Id.Text = string.Empty;
                scbClassification_Id.WaterText = "请选择物料分类";

                // 重置库存上限输入框
                stblimit.Text = string.Empty;
                stblimit.WaterText = "请输入库存上限";
                stblimit.SkinTxt.Text = string.Empty;
                stblimit.SkinTxt.WaterText = "请输入库存上限";

                // 重置库存下限输入框
                stblower.Text = string.Empty;
                stblower.WaterText = "请输入库存下限";
                stblower.SkinTxt.Text = string.Empty;
                stblower.SkinTxt.WaterText = "请输入库存下限";

                // 重置分页参数到初始状态
                PageIndex = 1;
                PageSize = 15;
                TotalCount = 0;
                TotalPages = 0;

                // 重新加载数据（显示所有数据，不带查询条件）
                GetData();

                // 显示重置成功提示
                MessageBox.Show("重置成功！所有查询条件已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 采购入库查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChlick_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            //入库单名称
            if (!string.IsNullOrWhiteSpace(tbxInputName.Text))
            {
                queryParams["warehouseReceiptName"] = tbxInputName.Text;
            }

            //来料检验单编号
            if (!string.IsNullOrWhiteSpace(tbxordernumber.Text))
            {
                queryParams["incomingNumber"] = tbxordernumber.Text;
            }
            //入库日期
            if (!string.IsNullOrWhiteSpace(skinDateTimePicker2.Text) && 
                DateTime.TryParse(skinDateTimePicker2.Text, out DateTime selectedDateIn))
            {
                // 仅保留日期部分（去除时间）
                DateTime dateOnly = selectedDateIn.Date;
                queryParams["warehousingDate"] = dateOnly.ToString("yyyy-MM-dd");
            }

            //生产日期
            if (!string.IsNullOrWhiteSpace(skinDateTimePicker4.Text) && 
                DateTime.TryParse(skinDateTimePicker4.Text, out DateTime selectedDatePro))
            {
                // 仅保留日期部分（去除时间）
                DateTime dateOnly = selectedDatePro.Date;
                queryParams["startDate"] = dateOnly.ToString("yyyy-MM-dd");
            }

            //到期日期
            if (!string.IsNullOrWhiteSpace(skinDateTimePicker3.Text) && 
                DateTime.TryParse(skinDateTimePicker3.Text, out DateTime selectedDateExp))
            {
                // 仅保留日期部分（去除时间）
                DateTime dateOnly = selectedDateExp.Date;
                queryParams["endDate"] = dateOnly.ToString("yyyy-MM-dd");
            }


            // 重置页码到第一页
            PageIndexIn = 1;
            
            // 调用改造后的 GetData，传入查询条件
            GetMaterialInputData(queryParams);
        }
        /// <summary>
        /// 采购入库的重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnreset_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置入库单名称输入框
                tbxInputName.Text = string.Empty;
                tbxInputName.WaterText = "请输入入库单名称";
                tbxInputName.SkinTxt.Text = string.Empty;
                tbxInputName.SkinTxt.WaterText = "请输入入库单名称";

                // 重置来料检验单编号输入框
                tbxordernumber.Text = string.Empty;
                tbxordernumber.WaterText = "请输入来料检验编号";
                tbxordernumber.SkinTxt.Text = string.Empty;
                tbxordernumber.SkinTxt.WaterText = "请输入来料检验编号";

                // 重置时间控件到当前日期
                skinDateTimePicker2.Text = DateTime.Now.ToString("yyyy-MM-dd");
                skinDateTimePicker2.text = "请选择入库日期";
                skinDateTimePicker3.Text = DateTime.Now.ToString("yyyy-MM-dd");
                skinDateTimePicker3.text = "请选择到期日期";
                skinDateTimePicker4.Text = DateTime.Now.ToString("yyyy-MM-dd");
                skinDateTimePicker4.text = "请选择生产日期";

                // 重置分页参数到初始状态
                PageIndexIn = 1;
                PageSizeIn = 15;
                TotalCountIn = 0;
                TotalPagesIn = 0;

                // 重新加载数据（显示所有数据，不带查询条件）
                GetMaterialInputData();

                // 显示重置成功提示
                MessageBox.Show("采购入库查询条件已重置！所有输入已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 采购入库的导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnExport_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                { "PageIndex", PageIndexIn.ToString() },
                { "PageSize", PageSizeIn.ToString() },
                { "Material_InOutType", "2" } // 只导出入库数据（采购入库）
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Material/GetMaterialInOutExport", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "采购入库导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"采购入库_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理"无保存权限"错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理"文件被占用"错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 生产领料添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtnAdd_Click(object sender, EventArgs e)
        {
            MaterialOutput output = new MaterialOutput();
            output.Show();
        }
        /// <summary>
        /// 生产领料显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetMaterialOutData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndexOut.ToString() },
                    { "PageSize", PageSizeOut.ToString() },
                    { "Material_InOutType", "1" } // 只显示出库数据（生产领料）
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                    // 调试输出：显示所有查询参数
                    Console.WriteLine($"查询参数: {kv.Key} = {kv.Value}");
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<MaterialOutputDtos>>>(
                    endpoint: "Material/GetMaterial_InOutboundShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 更新分页信息
                TotalCountIn = response.totalCount;
                TotalPagesIn = (response.totalCount + PageSizeIn - 1) / PageSizeIn;
                UpdatePageIn();
                // 将数据绑定到 DataGridView
                skinDataGridView1.DataSource = response.pageData;
                
                // 添加操作列
                AddMaterialOutputOperationColumns();
                
                // 先解绑之前的事件，避免重复绑定
                skinDataGridView1.CellClick -= SkinDataGridView1_CellClick;
                skinDataGridView1.CellFormatting -= SkinDataGridView1_CellFormatting;
                
                // 重新绑定单元格点击事件和格式化事件
                skinDataGridView1.CellClick += SkinDataGridView1_CellClick;
                skinDataGridView1.CellFormatting += SkinDataGridView1_CellFormatting;
              
            }
        }

        /// <summary>
        /// 为生产领料表格添加操作列
        /// </summary>
        private void AddMaterialOutputOperationColumns()
        {
            // 清除现有的操作列（如果存在）
            if (skinDataGridView1.Columns.Contains("CheckBox"))
            {
                skinDataGridView1.Columns.Remove("CheckBox");
            }
            if (skinDataGridView1.Columns.Contains("Output"))
            {
                skinDataGridView1.Columns.Remove("Output");
            }
            if (skinDataGridView1.Columns.Contains("Edit"))
            {
                skinDataGridView1.Columns.Remove("Edit");
            }
            if (skinDataGridView1.Columns.Contains("Delete"))
            {
                skinDataGridView1.Columns.Remove("Delete");
            }

            // 检查数据源中是否有数据
            if (skinDataGridView1.DataSource == null || skinDataGridView1.Rows.Count == 0)
            {
                return;
            }

            // 添加复选框列（放在最前面）
            var checkBoxCol = new DataGridViewCheckBoxColumn
            {
                Name = "CheckBox",
                HeaderText = "选择",
                Width = 50,
                TrueValue = true,
                FalseValue = false
            };
            skinDataGridView1.Columns.Insert(0, checkBoxCol);

            // 添加出库按钮列（始终添加，但通过CellFormatting事件控制显示）
            var outputCol = new DataGridViewButtonColumn
            {
                Name = "Output",
                HeaderText = "出库",
                Text = "出库",
                UseColumnTextForButtonValue = true,
                Width = 60
            };
            skinDataGridView1.Columns.Add(outputCol);

            // 添加编辑按钮列
            var editCol = new DataGridViewButtonColumn
            {
                Name = "Edit",
                HeaderText = "编辑",
                Text = "编辑",
                UseColumnTextForButtonValue = true,
                Width = 60
            };

            // 添加删除按钮列
            var deleteCol = new DataGridViewButtonColumn
            {
                Name = "Delete",
                HeaderText = "删除",
                Text = "删除",
                UseColumnTextForButtonValue = true,
                Width = 60
            };

            // 添加编辑和删除列到表格
            skinDataGridView1.Columns.Add(editCol);
            skinDataGridView1.Columns.Add(deleteCol);
        }

        /// <summary>
        /// 生产领料表格单元格格式化事件
        /// 用于控制出库按钮的显示/隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkinDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;

            // 只处理出库按钮列
            if (columnName == "Output")
            {
                // 获取当前行的数据
                if (grid.Rows[e.RowIndex].DataBoundItem is MaterialOutputDtos materialOutput)
                {
                    // 如果状态为true（已勾选），则隐藏出库按钮
                    if (materialOutput.Status)
                    {
                        // 将按钮文本设为空，实现隐藏效果
                        e.Value = "";
                        e.FormattingApplied = true;
                    }
                    else
                    {
                        // 如果状态为false（未勾选），则显示出库按钮
                        e.Value = "出库";
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        /// <summary>
        /// 生产领料表格单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkinDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;

            // 获取当前行的数据
            if (grid.Rows[e.RowIndex].DataBoundItem is MaterialOutputDtos materialOutput)
            {
                switch (columnName)
                {
                    case "Output":
                        // 检查状态，如果已勾选则不执行出库操作
                        if (materialOutput.Status)
                        {
                            MessageBox.Show("该记录状态已勾选，无法执行出库操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        
                        // 调用后端接口修改状态为已勾选
                        UpdateMaterialOutputStatus(materialOutput.Id, true);
                        break;

                    case "Edit":
                        // 编辑操作
                        MessageBox.Show($"编辑出库记录", "编辑", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 编辑完成后刷新数据
                        GetMaterialOutData();
                        break;

                    case "Delete":
                        // 删除操作
                        var result = MessageBox.Show($"确定要删除这条出库记录吗？", "确认删除", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        
                        if (result == DialogResult.Yes)
                        {
                            // 调用后端删除接口
                            DeleteMaterialOutputRecord(materialOutput.Id);
                        }
                        break;
                }
            }
        }

        /// <summary>
        /// 删除出库记录
        /// </summary>
        /// <param name="id">出库记录ID</param>
        private async void DeleteMaterialOutputRecord(int id)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的出库记录ID，无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除操作
                var result = MessageBox.Show($"确定要删除ID为 {id} 的出库记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 调用后端删除接口
                var response = await _apiClient.DeleteAsync<ApiResponse<string>>(
                    endpoint: "Material/DeleteMaterialInOut",
                    parameters: new Dictionary<string, string> { { "id", id.ToString() } }
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("出库记录删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 刷新数据
                    GetMaterialOutData();
                }
                else
                {
                    MessageBox.Show($"删除失败：{response?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除出库记录时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新出库记录状态
        /// </summary>
        /// <param name="id">出库记录ID</param>
        /// <param name="status">新状态</param>
        private async Task UpdateMaterialOutputStatus(int id, bool status)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的出库记录ID，无法更新状态", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 创建状态更新对象
                var statusUpdateData = new MaterialOutputStatusUpdateDto
                {
                    Id = id,
                    Status = status
                };

                // 构建查询参数
                var queryParams = new Dictionary<string, string>
                {
                    { "id", id.ToString() },
                    { "status", status.ToString().ToLower() }
                };
                
                // 构建带查询参数的endpoint
                var endpointWithParams = "Material/UpdateStatus?" + string.Join("&", 
                    queryParams.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
                
                var response = await _apiClient.PutAsync<object, ApiResponse<string>>(
                      endpoint: endpointWithParams,
                      data: null
                  );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("出库记录状态更新成功！", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新出库数据
                    GetMaterialOutData();
                    
                    // 勾选对应的复选框（根据id找到对应的行并勾选）
                    CheckCorrespondingCheckbox(id, status);
                }
                else
                {
                    // 业务报错（如"未找到记录"），回滚复选框状态
                    MessageBox.Show($"状态更新失败：{response?.message ?? "未知错误"}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

                
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新出库记录状态时发生错误：{ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);

              
            }
        }
       
        /// <summary>
        /// 生产领料的重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtnreset_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置领料单名称输入框
                tbxlingliao.Text = string.Empty;
                tbxlingliao.WaterText = "请输入领料名称";
                tbxlingliao.SkinTxt.Text = string.Empty;
                tbxlingliao.SkinTxt.WaterText = "请输入领料名称";

       
                // 重置任务编号输入框
                tbxrenwu.Text = string.Empty;
                tbxrenwu.WaterText = "请输任务编号";
                tbxrenwu.SkinTxt.Text = string.Empty;
                tbxrenwu.SkinTxt.WaterText = "请输入任务编号";

                // 重置工序名称输入框
                tbxgongxu.Text = string.Empty;
                tbxgongxu.WaterText = "请输入工序名称";
                tbxgongxu.SkinTxt.Text = string.Empty;
                tbxgongxu.SkinTxt.WaterText = "请输入工序名称";

      

                // 重置领料日期
                dtplingliaodate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                dtplingliaodate.text = "请选择领料日期";

                // 重置分页参数到初始状态
                PageIndexOut = 1;
                PageSizeOut = 15;
                TotalCountOut = 0;
                TotalPagesOut = 0;

                // 重新加载数据（显示所有数据，不带查询条件）
                GetMaterialOutData();

                // 显示重置成功提示
                MessageBox.Show("生产领料查询条件已重置！所有输入已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 生产领料查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnclick2_Click_1(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            // 领料单名称
            if (!string.IsNullOrWhiteSpace(tbxlingliao.Text))
            {
                queryParams["requisitionNumber"] = tbxlingliao.Text.Trim();
            }

         

            // 任务名称 - 注意：这里使用任务编号字段，因为界面上只有任务编号输入框
            // 如果需要按任务名称查询，需要添加对应的输入控件
            if (!string.IsNullOrWhiteSpace(tbxrenwu.Text))
            {
                queryParams["taskNumber"] = tbxrenwu.Text.Trim();
            }

            // 领料日期
            try
            {
                // 调试输出：显示控件的当前状态
                Console.WriteLine($"dtplingliaodate.Text: {dtplingliaodate.Text}");
                
                // 方法1：直接解析Text属性
                if (!string.IsNullOrWhiteSpace(dtplingliaodate.Text) && 
                    dtplingliaodate.Text != "请选择领料日期" &&
                    DateTime.TryParse(dtplingliaodate.Text, out DateTime parsedDate))
                {
                    DateTime dateOnly = parsedDate.Date;
                    queryParams["requisitionDate"] = dateOnly.ToString("yyyy-MM-dd");
                    Console.WriteLine($"领料日期查询参数: {dateOnly.ToString("yyyy-MM-dd")}");
                }
                // 方法2：尝试获取控件的SelectedDate属性（如果存在）
                else if (dtplingliaodate.GetType().GetProperty("SelectedDate") != null)
                {
                    var selectedDateProp = dtplingliaodate.GetType().GetProperty("SelectedDate");
                    var selectedDate = selectedDateProp.GetValue(dtplingliaodate);
                    if (selectedDate != null && selectedDate is DateTime)
                    {
                        DateTime dateOnly = ((DateTime)selectedDate).Date;
                        queryParams["requisitionDate"] = dateOnly.ToString("yyyy-MM-dd");
                        Console.WriteLine($"领料日期查询参数(SelectedDate): {dateOnly.ToString("yyyy-MM-dd")}");
                    }
                }
                // 方法3：尝试获取控件的DateTime属性（如果存在）
                else if (dtplingliaodate.GetType().GetProperty("DateTime") != null)
                {
                    var dateTimeProp = dtplingliaodate.GetType().GetProperty("DateTime");
                    var dateTime = dateTimeProp.GetValue(dtplingliaodate);
                    if (dateTime != null && dateTime is DateTime)
                    {
                        DateTime dateOnly = ((DateTime)dateTime).Date;
                        queryParams["requisitionDate"] = dateOnly.ToString("yyyy-MM-dd");
                        Console.WriteLine($"领料日期查询参数(DateTime): {dateOnly.ToString("yyyy-MM-dd")}");
                    }
                }
                else
                {
                    Console.WriteLine("领料日期控件没有有效值或无法获取日期");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理领料日期时出错: {ex.Message}");
            }

            // 工序名称
            if (!string.IsNullOrWhiteSpace(tbxgongxu.Text))
            {
                queryParams["processName"] = tbxgongxu.Text.Trim();
            }


            // 重置页码到第一页
            PageIndexOut = 1;
            
            // 调用查询方法，传入查询条件
            GetMaterialOutData(queryParams);
        }


        /// <summary>
        /// 勾选对应的复选框
        /// </summary>
        /// <param name="id">出库记录ID</param>
        /// <param name="status">状态值</param>
        private void CheckCorrespondingCheckbox(int id, bool status)
        {
            try
            {
                // 遍历出库数据表格，找到对应的行
                foreach (DataGridViewRow row in skinDataGridView1.Rows)
                {
                    if (row.DataBoundItem is MaterialOutputDtos materialOutput)
                    {
                        // 根据Id找到对应的行
                        if (materialOutput.Id == id)
                        {
                            // 更新数据对象的状态
                            materialOutput.Status = status;
                            
                            // 刷新表格显示
                            skinDataGridView1.Refresh();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"勾选复选框时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 勾选对应的入库复选框
        /// </summary>
        /// <param name="id">入库记录ID</param>
        /// <param name="status">状态值</param>
        private void CheckCorrespondingInputCheckbox(int id, bool status)
        {
            try
            {
                // 遍历入库数据表格，找到对应的行
                foreach (DataGridViewRow row in dgvMaterialInput.Rows)
                {
                    if (row.DataBoundItem is MaterialInputDtos materialInput)
                    {
                        // 根据Id找到对应的行
                        if (materialInput.Id == id)
                        {
                            // 更新数据对象的状态
                            materialInput.Status = status;

                            // 刷新表格显示
                            dgvMaterialInput.Refresh();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"勾选入库复选框时发生错误：{ex.Message}");
            }
        }

        private void UpdatePage() 
        {
            lbl分页.Text = $"第 {PageIndex} 页，共 {TotalPages} 页，总计 {TotalCount}条记录";
        }

        private void UpdatePageOut()
        {
            lbl生产领料.Text = $"第 {PageIndexOut} 页，共 {TotalPagesOut} 页，总计 {TotalCountOut}条记录 ";
        }

        private void UpdatePageIn()
        {
            lbl采购入库.Text = $"第 {PageIndexIn} 页，共 {TotalPagesIn} 页，总计 {TotalCountIn}条记录 ";
        }
        /// <summary>
        /// 生产领料的批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btndelete_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取选中的行
                var selectedIds = new List<int>();
                
                foreach (DataGridViewRow row in skinDataGridView1.Rows)
                {
                    if (row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value)
                    {
                        if (row.DataBoundItem is MaterialOutputDtos materialOutput)
                        {
                            selectedIds.Add(materialOutput.Id);
                        }
                    }
                }

                if (selectedIds.Count == 0)
                {
                    MessageBox.Show("请先选择要删除的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除
                var result = MessageBox.Show($"确定要删除选中的 {selectedIds.Count} 条记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    // 调用批量删除API
                    var response = await _apiClient.DeleteAsync<ApiResponse<string>>(
                        endpoint: "Material/BatchDeleteMaterialInOut",
                        parameters: new Dictionary<string, string>
                        {
                            { "id", string.Join(",", selectedIds) }
                        }
                    );

                    if (response != null && response.code == 200)
                    {
                        MessageBox.Show("批量删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 刷新数据
                        GetMaterialOutData();
                    }
                    else
                    {
                        MessageBox.Show($"删除失败：{response?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量删除时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 采购入库的批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnDeleteInput_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取选中的行
                var selectedIds = new List<int>();
                
                foreach (DataGridViewRow row in dgvMaterialInput.Rows)
                {
                    if (row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value)
                    {
                        if (row.DataBoundItem is MaterialInputDtos materialInput)
                        {
                            selectedIds.Add(materialInput.Id);
                        }
                    }
                }

                if (selectedIds.Count == 0)
                {
                    MessageBox.Show("请先选择要删除的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除
                var result = MessageBox.Show($"确定要删除选中的 {selectedIds.Count} 条记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    // 调用批量删除API
                    var response = await _apiClient.DeleteAsync<ApiResponse<string>>(
                        endpoint: "Material/BatchDeleteMaterialInOut",
                        parameters: new Dictionary<string, string>
                        {
                            { "id", string.Join(",", selectedIds) }
                        }
                    );

                    if (response != null && response.code == 200)
                    {
                        MessageBox.Show("批量删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 刷新数据
                        GetMaterialInputData();
                    }
                    else
                    {
                        MessageBox.Show($"删除失败：{response?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量删除时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 全选/取消全选生产领料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSelectAllOut_CheckedChanged(object sender, EventArgs e)
        {
            var isChecked = ((CheckBox)sender).Checked;
            foreach (DataGridViewRow row in skinDataGridView1.Rows)
            {
                if (row.Cells["CheckBox"] != null)
                {
                    row.Cells["CheckBox"].Value = isChecked;
                }
            }
        }

        /// <summary>
        /// 全选/取消全选采购入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSelectAllIn_CheckedChanged(object sender, EventArgs e)
        {
            var isChecked = ((CheckBox)sender).Checked;
            foreach (DataGridViewRow row in dgvMaterialInput.Rows)
            {
                if (row.Cells["CheckBox"] != null)
                {
                    row.Cells["CheckBox"].Value = isChecked;
                }
            }
        }

        /// <summary>
        /// 采购入库 - 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnpage_Click(object sender, EventArgs e)
        {
            if (PageIndexIn > 1)
            {
                PageIndexIn--;
                GetMaterialInputData();
            }
            else
            {
                MessageBox.Show("已经是第一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 采购入库 - 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsize_Click(object sender, EventArgs e)
        {
            if (PageIndexIn < TotalPagesIn)
            {
                PageIndexIn++;
                GetMaterialInputData();
            }
            else
            {
                MessageBox.Show("已经是最后一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }






        /// <summary>
        /// 采购合同跳转添加页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd1_Click(object sender, EventArgs e)
        {
            AddContract contract = new AddContract();
            contract.Show();
        }


        /// <summary>
        /// 采购合同显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetContractData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndexContract.ToString() },
                    { "PageSize", PageSizeContract.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<Procurement_ContractOutput>>>(
                    endpoint: "Material/GetProcurement_Contract",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 更新分页信息
                TotalCountContract = response.totalCount;
                TotalPagesContract = (response.totalCount + PageSize - 1) / PageSize;

                // 将数据绑定到 DataGridView
                dgvContract.DataSource = response.pageData;

                AddContractOperationColumns();

                // 绑定操作按钮事件（避免重复绑定）
                dgvContract.CellClick -= DgvContract_CellClick;
                dgvContract.CellClick += DgvContract_CellClick;

                UpdatePageContract();
            }
        }

        /// <summary>
        /// 为采购合同表格添加复选框列
        /// </summary>
        private void AddContractOperationColumns()
        {
            // 数据无行时不添加
            if (dgvContract.DataSource == null || dgvContract.Rows.Count == 0)
            {
                return;
            }

            // 确保复选框列存在（放在最前）
            if (!dgvContract.Columns.Contains("CheckBox"))
            {
                var checkBoxCol = new DataGridViewCheckBoxColumn
                {
                    Name = "CheckBox",
                    HeaderText = "选择",
                    Width = 50,
                    TrueValue = true,
                    FalseValue = false
                };
                dgvContract.Columns.Insert(0, checkBoxCol);
            }

            // 先移除已有的操作列，避免重复
            if (dgvContract.Columns.Contains("GeneratePO"))
            {
                dgvContract.Columns.Remove("GeneratePO");
            }
            if (dgvContract.Columns.Contains("Edit"))
            {
                dgvContract.Columns.Remove("Edit");
            }
            if (dgvContract.Columns.Contains("Delete"))
            {
                dgvContract.Columns.Remove("Delete");
            }

            // 找到"含税价格"列的位置（优先用 DataPropertyName，其次用 HeaderText）
            int insertIndex = dgvContract.Columns.Count; // 默认插在末尾
            foreach (DataGridViewColumn col in dgvContract.Columns)
            {
                if ((col.DataPropertyName == "Taxed_Price") || (col.HeaderText == "含税价格"))
                {
                    insertIndex = col.DisplayIndex + 1;
                    break;
                }
            }

            // 构建三个按钮列
            var generateCol = new DataGridViewButtonColumn
            {
                Name = "GeneratePO",
                HeaderText = "操作",
                Text = "生成采购单",
                UseColumnTextForButtonValue = true,
                Width = 90
            };
            var editCol = new DataGridViewButtonColumn
            {
                Name = "Edit",
                HeaderText = "",
                Text = "编辑",
                UseColumnTextForButtonValue = true,
                Width = 60
            };
            var deleteCol = new DataGridViewButtonColumn
            {
                Name = "Delete",
                HeaderText = "",
                Text = "删除",
                UseColumnTextForButtonValue = true,
                Width = 60
            };

            // 插入到"含税价格"之后，保持相对顺序
            dgvContract.Columns.Add(generateCol);
            dgvContract.Columns.Add(editCol);
            dgvContract.Columns.Add(deleteCol);

            // 设置显示顺序（DisplayIndex）以保证位置
            generateCol.DisplayIndex = insertIndex;
            editCol.DisplayIndex = insertIndex + 1;
            deleteCol.DisplayIndex = insertIndex + 2;
        }

        // 采购合同表格按钮点击处理
        private void DgvContract_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;

            if (grid.Rows[e.RowIndex].DataBoundItem is Procurement_ContractOutput contract)
            {
                switch (columnName)
                {
                    case "GeneratePO":
                        // 显示确认提示
                        var result = MessageBox.Show($"是否生成采购单？\n合同名称：{contract.ContractName}\n签订日期：{contract.SignDate:yyyy-MM-dd}\n税率：{contract.Tax_Rate}%\n未税价格：{contract.Untaxed_Price}\n含税价格：{contract.Taxed_Price}", 
                            "确认生成采购单", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        
                        if (result == DialogResult.Yes)
                        {
                            // 调用生成采购单方法
                            GeneratePurchaseOrder(contract);
                        }
                        break;
                    case "Edit":
                        MessageBox.Show($"编辑合同：{contract.ContractName}", "编辑", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    case "Delete":
                        var deleteResult = MessageBox.Show("确定要删除该合同吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (deleteResult == DialogResult.Yes)
                        {
                            DeleteContractRecord(contract.Id);
                        }
                        break;
                }
            }
        }

        /// <summary>
        /// 删除采购合同
        /// </summary>
        /// <param name="id">出库记录ID</param>
        private async void DeleteContractRecord(int id)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的出库记录ID，无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除操作
                var result = MessageBox.Show($"确定要删除ID为 {id} 的出库记录吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                {
                    return;
                }

                // 调用后端删除接口
                var response = await _apiClient.DeleteAsync<ApiResponse<string>>(
                    endpoint: "Material/DeleteProcurementContract",
                    parameters: new Dictionary<string, string> { { "id", id.ToString() } }
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("采购合同删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 刷新数据（刷新采购合同列表）
                    GetContractData();
                }
                else
                {
                    MessageBox.Show($"删除失败：{response?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除采购合同时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 供应商下来框
        /// </summary>
        private async void LoadSupplierData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<SupplierInput>>>(
                    endpoint: "Material/GetSupplier_TableShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    cbxsupplier.Items.Clear();
                    cbxsupplier.DisplayMember = "supplierName";
                    cbxsupplier.ValueMember = "id";
                    cbxsupplier.DataSource = deptResponse.data;
                    cbxsupplier.SelectedIndex = -1;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 采购合同的查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnclick1_Click(object sender, EventArgs e)
        {

            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(tbxhetong.Text))
            {
                queryParams["contractName"] = tbxhetong.Text;
            }

            // 类型ID（从下拉框选的值）
            if (cbxsupplier.SelectedValue != null)
            {
                queryParams["supplier_Id"] = ((int)cbxsupplier.SelectedValue).ToString();
            }
            //入库日期
            if (!string.IsNullOrWhiteSpace(dtpDate1.Text) &&
                DateTime.TryParse(dtpDate1.Text, out DateTime selectedDateIn))
            {
                // 仅保留日期部分（去除时间）
                DateTime dateOnly = selectedDateIn.Date;
                queryParams["signDate"] = dateOnly.ToString("yyyy-MM-dd");
            }

            // 重置页码到第一页
            PageIndexContract = 1;

            // 调用改造后的 GetData，传入查询条件
            GetContractData(queryParams);
        }
        /// <summary>
        /// 采购合同的重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnchongzhi1_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置领料单名称输入框
                tbxhetong.Text = string.Empty;
                tbxhetong.WaterText = "请输入合同名称";
                tbxhetong.SkinTxt.Text = string.Empty;
                tbxhetong.SkinTxt.WaterText = "请输入合同名称";


                // 重置物料属性下拉框
                cbxsupplier.SelectedIndex = -1;
                cbxsupplier.Text = string.Empty;
                cbxsupplier.WaterText = "请选择供应商";


                // 重置领料日期
                dtpDate1.Text = DateTime.Now.ToString("yyyy-MM-dd");
                dtpDate1.text = "请选择签订日期";

                // 重置分页参数到初始状态
                PageIndexContract = 1;
                PageSizeContract = 15;
                TotalCountContract = 0;
                TotalPagesContract = 0;

                // 重新加载数据（显示所有数据，不带查询条件）
                GetContractData();

                // 显示重置成功提示
                MessageBox.Show("采购合同查询条件已重置！所有输入已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 采购合同的导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnExport1_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                { "PageIndex", PageIndexContract.ToString() },
                { "PageSize", PageSizeContract.ToString() },
               
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Material/GetProcurementContractExport", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "采购入库导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"采购合同_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理"无保存权限"错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理"文件被占用"错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        /// <summary>
        /// 采购合同的分页
        /// </summary>
        private void UpdatePageContract()
        {
            lbl采购合同.Text = $"第 {PageIndexContract} 页，共 {TotalPagesContract} 页，总计 {TotalCountContract}条记录 ";
        }
        /// <summary>
        /// 采购合同的上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnonepage_Click(object sender, EventArgs e)
        {
            if (PageIndexContract > 1)
            {
                PageIndexContract--;
                GetContractData();
            }
            else
            {
                MessageBox.Show("已经是第一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 采购合同的下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btntwopage_Click(object sender, EventArgs e)
        {
            if (PageIndexContract < TotalPagesContract)
            {
                PageIndexContract++;
                GetContractData();
            }
            else
            {
                MessageBox.Show("已经是最后一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 采购合同的审核按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAudit_Click(object sender, EventArgs e)
        {
            // 收集勾选的合同ID
            var selectedIds = new List<int>();
            foreach (DataGridViewRow row in dgvContract.Rows)
            {
                if (row.Cells["CheckBox"] != null && row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value)
                {
                    if (row.DataBoundItem is Procurement_ContractOutput contract)
                    {
                        // 已审核的跳过
                        if (!string.IsNullOrWhiteSpace(contract.Audit) && contract.Audit == "已审核")
                        {
                            continue;
                        }
                        selectedIds.Add(contract.Id);
                    }
                }
            }

            if (selectedIds.Count == 0)
            {
                MessageBox.Show("请先勾选需要审核的合同！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var result = MessageBox.Show("确认要审核吗？", "审核确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes)
            {
                return;
            }

            // 执行审核（修改为已审核）
            foreach (var id in selectedIds)
            {
                UpdateContractStatus(id, "已审核");
            }
        }
        /// <summary>
        /// 采购合同的修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="audit"></param>
        private async void UpdateContractStatus(int id, string audit)
        {
            try
            {
                // 验证ID是否有效
                if (id <= 0)
                {
                    MessageBox.Show("无效的入库记录ID，无法更新状态", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 创建状态更新对象
                var statusUpdateData = new ContractStatusUpdateDto
                {
                    Id = id,
                    Audit = audit
                };

                // 直接以请求体方式提交（后端要求 Audit 为必填）
                var response = await _apiClient.PutAsync<ContractStatusUpdateDto, ApiResponse<string>>(
                      endpoint: "Material/UpdateAuditStatus",
                      data: statusUpdateData
                  );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("采购合同记录状态更新成功！", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新入库数据
                    GetContractData();

                   
                }
                else
                {
                    // 业务报错（如"未找到记录"），回滚复选框状态
                    MessageBox.Show($"状态更新失败：{response?.message ?? "未知错误"}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新采购合同记录状态时发生错误：{ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);


            }
        }

        /// <summary>
        /// 生成采购单
        /// </summary>
        /// <param name="contract">采购合同信息</param>
        private async void GeneratePurchaseOrder(Procurement_ContractOutput contract)
        {
            try
            {
                // 验证必要字段
                if (contract.Supplier_Id == null || contract.Supplier_Id <= 0)
                {
                    MessageBox.Show("合同信息中缺少有效的供应商ID，无法生成采购单", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (contract.Material_Id <= 0)
                {
                    MessageBox.Show("合同信息中缺少有效的物料ID，无法生成采购单", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 生成采购单号（采购单六、采购单七等）
                string purchaseNumber = await GenerateNextPurchaseNumber();
                
                // 创建采购单DTO
                var purchaseDto = new AddPurchaseDtos
                {
                    Purchase_Number = purchaseNumber,
                    SignDate = contract.SignDate ?? DateTime.Now,
                    PricingId = 0, // 根据需求设置
                    SupplierId = contract.Supplier_Id.Value, // 从合同信息中获取供应商ID
                    Tax_Rate = contract.Tax_Rate.ToString(),
                    Tax_Type = "应税内含", // 固定值
                    Tax_Wei = contract.Untaxed_Price.ToString(),
                    Tax_Han = contract.Taxed_Price.ToString(),
                    MaterialId = contract.Material_Id // 从合同信息中获取物料ID
                };

                // 调用后端API添加采购单 - 使用Material模块的API端点
                var response = await _apiClient.PostAsync<AddPurchaseDtos, ApiResponse<string>>(
                    endpoint: "Material/AddPurchase",
                    data: purchaseDto
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show($"采购单生成成功！\n采购单号：{purchaseNumber}\n合同名称：{contract.ContractName}", 
                        "生成成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 刷新采购合同数据
                    GetContractData();
                }
                else
                {
                    MessageBox.Show($"采购单生成失败：{response?.message ?? "未知错误"}", 
                        "生成失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成采购单时发生错误：{ex.Message}", 
                    "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 生成下一个采购单号
        /// </summary>
        /// <returns>下一个采购单号</returns>
        private async Task<string> GenerateNextPurchaseNumber()
        {
            try
            {
                // 获取现有的采购单数量，用于生成下一个编号
                var response = await _apiClient.GetAsync<ApiResponse<List<PurchaseOutput>>>(
                    endpoint: "Material/GetPurchaseShow",
                    parameters: new Dictionary<string, string>
                    {
                        { "PageIndex", "1" },
                        { "PageSize", "1000" } // 获取足够多的数据来计算总数
                    }
                );

                if (response != null && response.code == 200)
                {
                    // 计算下一个编号（采购单六、采购单七等）
                    int nextNumber = response.totalCount + 1;
                    return $"采购单{ConvertToChineseNumber(nextNumber)}";
                }
                else
                {
                    // 如果获取失败，使用当前时间生成
                    return $"采购单{DateTime.Now:yyyyMMddHHmmss}";
                }
            }
            catch (Exception)
            {
                // 异常情况下使用当前时间生成
                return $"采购单{DateTime.Now:yyyyMMddHHmmss}";
            }
        }

        /// <summary>
        /// 将数字转换为中文数字
        /// </summary>
        /// <param name="number">数字</param>
        /// <returns>中文数字</returns>
        private string ConvertToChineseNumber(int number)
        {
            if (number <= 0) return "零";
            
            string[] chineseNumbers = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
            
            if (number <= 10)
            {
                return chineseNumbers[number];
            }
            else if (number < 20)
            {
                return "十" + (number == 10 ? "" : chineseNumbers[number - 10]);
            }
            else if (number < 100)
            {
                int tens = number / 10;
                int ones = number % 10;
                string result = chineseNumbers[tens] + "十";
                if (ones > 0)
                {
                    result += chineseNumbers[ones];
                }
                return result;
            }
            else
            {
                // 对于大于100的数字，使用阿拉伯数字
                return number.ToString();
            }
        }

        /// <summary>
        /// 测试采购单生成功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestPurchaseOrder_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建一个测试合同对象
                var testContract = new Procurement_ContractOutput
                {
                    Id = 1,
                    ContractNumber = "TEST001",
                    ContractName = "测试合同",
                    SignDate = DateTime.Now,
                    Supplier_Id = 1, // 测试供应商ID
                    SupplierName = "测试供应商",
                    Tax_Rate = 13,
                    Untaxed_Price = 1000.00m,
                    Taxed_Price = 1130.00m,
                    Material_Id = 1 // 测试物料ID
                };

                // 调用生成采购单方法
                GeneratePurchaseOrder(testContract);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"测试采购单生成时发生错误：{ex.Message}", "测试错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



    }
}
